//
//  SearchCommunityViewController.m
//  cityStar
//
//  Created by joyban on 15-3-8.
//  Copyright (c) 2015年 tiny. All rights reserved.
//

#import "SearchCommunityViewController.h"
#import "SearchCommunityCell.h"
#import <CoreLocation/CoreLocation.h>
#import "SVPullToRefresh.h"
#import "CitylistsModel.h"
#import "BindingViewController.h"

NSString *const SearchCommunityCellID = @"SearchCommunityCellID";

@interface SearchCommunityViewController ()<CLLocationManagerDelegate,UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UITableView *SearchTabelView;
@property (nonatomic, strong) NSMutableArray *arrayRequest;
@property (retain, nonatomic) CLLocationManager *locManager;
@property (nonatomic, assign) CLLocationCoordinate2D loc;
@property (nonatomic, assign) int page;
@property (nonatomic, assign) NSString * searchid;


@end

@implementation SearchCommunityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpTableViews];
//    [self webRequest_GetMyUserCity];
    self.arrayRequest = [[NSMutableArray alloc]init];
    self.locManager = [[CLLocationManager alloc]init];
    //设置代理
    self.locManager.delegate = self;
    //设置位置经度
    self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置每隔100米更新位置
    self.locManager.distanceFilter = 100;
    //开始定位服务
    [self.locManager startUpdatingLocation];
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)goBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
}

#pragma mark - locationDelegate
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

//协议中的方法，作用是每当位置发生更新时会调用的委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //结构体，存储位置坐标
    self.loc = [newLocation coordinate];
    NSString *postUrl  = [NSString stringWithFormat:@"%@%f/%f",KInterFace_location,self.loc.latitude,self.loc.longitude];
    [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            NSString *str = response[@"value"][@"detail"][@"city_code"];
            self.searchid = str;
            
            NSString *postUrl  = [NSString stringWithFormat:@"%@/x/%f/y/%f",KinterFace_Citylists,self.loc.longitude,self.loc.latitude];
            [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
                if (success) {
                    self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][@"content"]];
                    
//                    __weak typeof(self)weakSelf = self;
//                    
//                    [self.SearchTabelView addPullToRefreshWithActionHandler:^{
//                        self.page = 1;
//                        [weakSelf webRequest_SearchOrLists:NO];
//                    }];
//                    [self.SearchTabelView addInfiniteScrollingWithActionHandler:^{
//                        [weakSelf webRequest_SearchOrLists:YES];
//                    }];
//                    [self.SearchTabelView triggerPullToRefresh];
                    
                    [self.SearchTabelView reloadData];


                }else{
                    [SVProgressHUD showErrorWithStatus:errMsg];
                }
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}

-(IBAction)didSearch_Action:(UIButton *)sender {
    self.page = 1;
    [self webRequest_GetListsMore:NO];
}

-(void)webRequest_SearchOrLists:(BOOL)isMore
{
    if([self.searchBar.text isEqualToString:@""])
    {
        [self webRequest_GetListsMore:isMore];
    }else{
        [self webRequest_GetSearchMore:isMore];
    }
}

-(void)webRequest_GetSearchMore:(BOOL)isMore
{
    NSString *postUrl  = [NSString stringWithFormat:@"%@/x/%f/y/%f/p/%d",KinterFace_Citylists,self.loc.longitude,self.loc.latitude,isMore?self.page:0];
    [HttpRequestManager getMethod:[postUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            if (isMore) {
                [self.arrayRequest addObjectsFromArray:response[@"value"][@"content"]];
                self.page = self.page + 1;
            }else{
                if (response[@"value"][@"content"]) {
                    self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][@"content"]];
                }
            }
            [self.SearchTabelView reloadData];
        }
        if (isMore) {
            [self.SearchTabelView.infiniteScrollingView stopAnimating];
        }else{
            [self.SearchTabelView.pullToRefreshView stopAnimating];
        }
    }];
}

-(void)webRequest_GetListsMore:(BOOL)isMore
{
//    NSString *postUrl = [NSString stringWithFormat:@"%@/name/%@/city/%@/page/%d",KinterFace_CitySearch,self.searchBar.text,self.searchid,isMore?self.page:0];
    NSString *postUrl = [NSString stringWithFormat:@"%@/name/%@/city/%@/page/%i",KinterFace_CitySearch,self.searchBar.text,self.searchid,0];
    [HttpRequestManager getMethod:[postUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
            if (isMore) {
                [self.arrayRequest addObjectsFromArray:response[@"value"][@"content"]];
                self.page = self.page + 1;
            }else{
                self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][@"content"]];
            }
            [self.SearchTabelView reloadData];
        }
        if (isMore) {
            [self.SearchTabelView.infiniteScrollingView stopAnimating];
        }else{
            [self.SearchTabelView.pullToRefreshView stopAnimating];
        }
    }];
}

-(void)setUpTableViews
{
    [self.SearchTabelView registerNib:[SearchCommunityCell nib] forCellReuseIdentifier:SearchCommunityCellID];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [super viewWillAppear:animated];
//    [self.searchBar becomeFirstResponder];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [self.searchDisplayController.searchBar becomeFirstResponder];
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [SearchCommunityCell heightOfTableCell];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayRequest.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchCommunityCell *CommunityCell = [tableView dequeueReusableCellWithIdentifier:SearchCommunityCellID];
    CitylistsModel *model = [CitylistsModel objectFromDictionary:self.arrayRequest[indexPath.row]];
    [CommunityCell setDataListsModel:model];
    CommunityCell.selectionStyle = UITableViewCellSelectionStyleGray;
    return CommunityCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CitylistsModel *model = [CitylistsModel objectFromDictionary:self.arrayRequest[indexPath.row]];
    BindingViewController *BingdingVC = [[BindingViewController alloc]initWithLocationMessage:model andRightBtn:YES];
    BingdingVC.listsmodel = model;
    BingdingVC.cityId =[NSString stringWithFormat:@"%@",self.arrayRequest[indexPath.row][@"id"]];
    [self.navigationController pushViewController:BingdingVC animated:YES];
    [tableView reloadData];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
